/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/

#define MAP_FILE_NAME "../../res/autmap-small.txt"

#include<stdio.h>
#include<stdlib.h>
#include<math.h>

#include "TOccupancyGrid.h" ///< Occupancy grid class
#include "CParticleFilter.h"
#include "glutImageGUI.h"   ///< For visualisation
#include "JPEGEncoder.hpp"  ///< For saving JPEG
		
float topi(float da){
	if(da>M_PI)while(da>M_PI) da-=2.0*M_PI;
	else if(da<-M_PI)while(da<-M_PI) da+=2.0*M_PI;
	return da;
}

///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
/// Read Scan measurement file with arbitrary number of items (and allowing white space before '\n')
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
int forwardString(const char *buf, int begin,int items){
		int i=begin+1;
		int cnt = 0;
		while(cnt<items){
				if(buf[i]==' ') cnt++;
				i++;
		}
		return i;
}

/// For reading the data from file
int readScanLine(FILE *f,Grid::TScan &meas, Grid::pose &p ){
		float time_s;
		int i=0;
		char in_line[16096];
		char *ret;
		char c=0;
		
		ret = fgets (in_line, 16096, f );
		if(ret==NULL){
				if(feof(f)){
						fprintf(stderr,"Reached end of file -- Alles klar!\n");
						return 0;
				}else{
						fprintf(stderr,"Some error occurred...sorry contact Jari :)\n");
						return 1;
				}
		}
		int cnt=0;
		while( (c!='\n')){
				if(in_line[i]==' ') cnt++;
				else if(in_line[i]=='\n') break;
				i++;
		}
		//fprintf(stderr,"There is %d floats in this file (= %d meas points)\n",cnt,(cnt-3)/2);
		sscanf(in_line,"%f %f %f ",&p.x,&p.y,&p.a); ///< Pose header
		int pointer_ind=0;
		pointer_ind = forwardString(in_line,0,3); ///search the next begin for float
		meas.N = (cnt-3)/2;
		i =0;
		while(i<((cnt-3)/2)){
				sscanf((in_line+pointer_ind),"%f %f",&meas.r[i],&meas.a[i]);
				pointer_ind = forwardString(in_line,pointer_ind,2); ///search the next begin for float
				i++;
		}
	
		return 0;
}

//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
///DRAWING STUFF
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
void setRGBpix(unsigned char *rgb,int i,int j, int Nx, unsigned char r,unsigned char g, unsigned char b ){
		rgb[3*Nx*j+3*i]=r;
		rgb[3*Nx*j+3*i+1]=g;
		rgb[3*Nx*j+3*i+2]=b;
}

void setRGBmap(unsigned char *rgb,TOccupancyGrid *gr, unsigned char r,unsigned char g, unsigned char b){
		float *data = gr->getDataPtr();
		int Nx,Ny;
		gr->getDim(Nx,Ny);
		float v;
	
		for(int j=0;j<Ny;j++){
				for(int i=0;i<Nx;i++){
						v = data[Nx*j+i];
						if(v>0.6) v = 0; else v = 0.99; 
				
						setRGBpix(rgb,i,j, Nx, r*v,g*v,b*v);
				}
		}	
}

void setRGBpixBold(unsigned char *rgb,int i,int j, int Nx, unsigned char r,unsigned char g, unsigned char b){
		for(int ii=i-1;ii<i+1;ii++){
				for(int jj=j-1;jj<j+1;jj++){
						setRGBpix(rgb,ii,jj,Nx,r,g,b);
				}
		}

}

void drawLine(unsigned char *RGB, int Nx,int Ny,float resolution,   ///Grid parameters
							uint pix, uint piy,float angle, float length, ///< Start pixel, angle to draw and linelength
							unsigned char r,unsigned char g,unsigned char b){
									float dy = sin(angle);
									float dx = cos(angle);
									float rr=0;
									int i=0;
									uint x,y;
									while(rr<length){
											x = pix + i*dx;
											y = piy - i*dy;
											setRGBpixBold(RGB,x,y, Nx, r,g,b);
											i++;
											rr+=resolution;
									}
}

void drawLineThin(unsigned char *RGB, int Nx,int Ny,float resolution,   ///Grid parameters
							uint pix, uint piy,float angle, float length, ///< Start pixel, angle to draw and linelength
							unsigned char r,unsigned char g,unsigned char b){
									float dy = sin(angle);
									float dx = cos(angle);
									float rr=0;
									int i=0;
									uint x,y;
									while(rr<length){
											x = pix + i*dx;
											y = piy - i*dy;
											setRGBpix(RGB,x,y, Nx, r,g,b);
											i++;
											rr+=resolution;
									}
							}

void drawCross(unsigned char *RGB, int Nx,int Ny,float resolution,   ///Grid parameters
							uint pix, uint piy, float length, ///< Start pixel, angle to draw and linelength
							unsigned char r,unsigned char g,unsigned char b){
		float angle = M_PI/4;
		for(int i=0;i<3;i++){
				drawLineThin(RGB, Nx,Ny,resolution, pix, piy,angle, length, r,g,b);
				angle+=M_PI/2;
		}
}


void saveJPEG(const char *fname, unsigned char *rgb,int Nx, int Ny){
		CJPEGEncoder encoder;
		encoder.SetRGBDataPtr((const char *)rgb,Nx,Ny);
		FILE *f = fopen(fname,"wb");
		fwrite(encoder.GetJPEGDataPtr(), 
					 encoder.GetJPEGDataSize(), 
					 1, f);
		fclose(f);
		
}

float randomi(){
	return (2.0 * (float)(rand()%10000) - 1.0)/10000.0;
}

//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////

void saveScan(const char *fname, Grid::TScan &s){
		FILE *f = fopen(fname,"wt");
		if(f==NULL){
				fprintf(stderr,"Not good - unable to save!\n");
				exit(1);
		}

		for(int i=0;i<s.N;i++){
				fprintf(f,"%f %f\n",s.r[i],s.a[i]);
		}
		fclose(f);
}

void printUsage(){
		fprintf(stderr,"\n-----------------------------------------------------------------\n");
		fprintf(stderr,"Plots a batch of scans from a log file\n");
		fprintf(stderr,"Usage: ./plot_scan_measurement [in_file]\n");
		fprintf(stderr,"if [in_file] is not given the default file is LnMlib/data/j2b2_measurement.txt\n");
		fprintf(stderr,"\nThe output is saved to 'out_result.jpg'\n");
		fprintf(stderr,"-----------------------------------------------------------------\n\n");
}



int main(int argc, char *argv[]){
		const char *measurement_file_name="../../../data/j2b2_measurement.txt";
		//float grid_size = 30.0; ///< size of the local grid
		float grid_size = 140.0; ///< size of the local grid
		int enough_scan_poinsts = 800; ///< enough to reserve memory for the scan points in the meas file.
		
		TOccupancyGrid O(grid_size,grid_size,0.08,Grid::TCoord2D(0,0));
		O.setGridToValue(0.5);
		
		Grid::TScan meas;
		meas.alloc(enough_scan_poinsts);
		Grid::pose pos;
		std::vector< Grid::pose > poses;    ///All poses for previous map
		printUsage();
		if(argc == 2) measurement_file_name = argv[1];
		
		int Nx,Ny;	
		unsigned char *rgb;
		O.getDim(Nx,Ny);
		rgb = (unsigned char *) malloc(3*Nx*Ny);
		
		addImageWindow(Nx, Ny);
		glutImageGUI_Start();
		
		FILE *log = fopen(measurement_file_name,"rt"); ///< data file
		if(log == NULL){
				fprintf(stderr,"Unable to open the log file\n");
				exit(1);
		}
		int cnt = 0;
	
		while(!feof(log)){
				readScanLine(log,meas,pos);
				poses.push_back(pos);
				meas.filt(60.0);
				//meas.filt(4.095);
				O.setScanFillProb(pos.x, pos.y ,pos.a,meas,0.3,0.9);
				if(cnt%10==0){
						O.fillRGB(rgb,1.0/255.0);
						for(int i=0;i<poses.size();i++){
								Grid::TPixel pix = O.toPixel(Grid::TCoord2D(poses[i].x,poses[i].y));
								setRGBpix(rgb,pix.x,pix.y, Nx, 255,0, 0 );
						}
						displayImage(0, rgb,Ny,Nx);
				}
				cnt++;
		}
		fprintf(stderr,"\n ######   THE END - CTRL-C Ends the show   ######\n");
		cnt = 0;
		while(1){
				O.fillRGB(rgb,1.0/255.0);
				for(int i=0;i<poses.size();i++){
						Grid::TPixel pix = O.toPixel(Grid::TCoord2D(poses[i].x,poses[i].y));
						setRGBpix(rgb,pix.x,pix.y, Nx, 255,0, 0 );
				}
				displayImage(0, rgb,Ny,Nx);
				if(cnt ==0){
						saveJPEG("out_result.jpg", rgb,Nx,Ny);
						cnt++;
				}
				usleep(1000*100);
				
		}
		
		
		free(rgb);
		
		return 0;
}		
